package com.rtf.framework.monitor.support;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 基于url拦截器
 * @Author : liupeng
 * @Date : 2020-02-01
 * @Modified By
 */
@Slf4j
public class AppUrlTraceInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle( HttpServletRequest request,
                              HttpServletResponse response, Object handler)
            throws Exception {
        long startTime = System.currentTimeMillis() ;

        request.setAttribute( "_startTime" , startTime ) ;

        return true;
    }

    @Override
    public void afterCompletion( HttpServletRequest request,
                                 HttpServletResponse response, Object handler, Exception ex) throws Exception {
        if( request.getAttribute( "_startTime" ) == null ){
            return;
        }

        // 获取异常信息
        Object exceptionName = request.getAttribute("exception_name") ;
        if( exceptionName == null || !StringUtils.hasText( exceptionName.toString() )){
            exceptionName = ex ;
        }

        try{
            // 计算开始时间和技术时间
            Long startTime = (Long) request.getAttribute( "_startTime" ) ;
            long endTime = System.currentTimeMillis() ;
            // 计算请求时长，毫秒
            long duration = endTime - startTime ;
            AppRequestPool.recordRequestInfo( endTime , request.getRequestURI() , duration ,
                    exceptionName==null || !StringUtils.hasText( exceptionName.toString() )) ;
        }catch( Exception e ){
            log.error( "请求响应时间跟踪异常 : {}" , e ) ;
        }
    }

}